<?php
use App\Helpers\utils\WeChat\AiSpeech;
use App\Helpers\utils\WeChat\OfficialAccount;
use App\Models\Setting;
use Illuminate\Support\Facades\Log;

function rsp($data = 20000)
{
    $messages = config('errors');
    if (is_numeric($data)) {
        return [
            'code' => $data,
            'data' => $messages[$data]
        ];
    } else {
        return [
            'code' => 20000,
            'data' => $data
        ];
    }
}

/**
 * 对象转数组
 * @param $array
 * @return array
 */
function object2array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    }
    if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object2array($value);
        }
    }
    return $array;
}

/**
 * 检查setting对应的配置是否过期
 * @param $key
 * @return string
 */
function checkSetting($key)
{
    $setting = Setting::where('key', $key)->first();
    $notExit = false;
    $expireStatus = false;
    if (empty($setting)) {
        $notExit = true;
    } else {
        if ($setting['expire'] != -1) {
            $time = strtotime($setting['updated_at']);
            if ($time + $setting['expire'] < time()) {
                $expireStatus = true;
            }
        }
    }
    if ($notExit || $expireStatus) {
        if ($notExit) {
            $setting = new Setting();
        }
        switch ($key) {
            case 'ai_signature': {
                $ai = new AiSpeech();
                $rsp = $ai->sign();
                $setting['value'] = $rsp['signature'];
                $setting['expire'] = $rsp['expiresIn'];
                break;
            }
            case 'access_token': {
                $wx = new OfficialAccount();
                $rsp = $wx->getAccessToken();
                $setting['value'] = $rsp['access_token'];
                $setting['expire'] = $rsp['expires_in'];
            }
            default: break;
        }
        $setting['key'] = $key;
        $setting->save();
    }
    return $setting['value'];
}
